﻿using System.Linq;

using NServiceBus;

using TheKitchen.Events;
using TheKitchen.Querying.Core.DataAccess;

namespace TheKitchen.Querying.Core.Denormalizers
{
    public class RecipesDenormalizer : IHandleMessages<NewRecipeCreated>, IHandleMessages<RecipeRated>
    {
        public void Handle(NewRecipeCreated message)
        {
            using (var ctx = new QueryContext())
            {
                var recipe = new Recipe
                {
                    Id = message.Id,
                    Version = message.Version,
                    Name = message.Name,
                    Description = message.Description
                };

                ctx.Add(recipe);
            }
        }

        public void Handle(RecipeRated message)
        {
            using (var ctx = new QueryContext())
            {
                Recipe recipe = ctx.Recipes.Single(r => r.Id == message.Id);
                recipe.Version = message.Version;
                recipe.Rating = message.Rating;

                ctx.Session.Flush();
            }
        }
    }
}